package com.wgb.movie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wgb.movie.annotation.AuthCheck;
import com.wgb.movie.common.BaseResponse;
import com.wgb.movie.common.DeleteRequest;
import com.wgb.movie.common.ErrorCode;
import com.wgb.movie.common.ResultUtils;
import com.wgb.movie.constant.UserConstant;
import com.wgb.movie.exception.BusinessException;
import com.wgb.movie.exception.ThrowUtils;
import com.wgb.movie.model.dto.movieEvaluation.MovieEvaluationAddRequest;
import com.wgb.movie.model.dto.movieEvaluation.MovieEvaluationEditRequest;
import com.wgb.movie.model.dto.movieEvaluation.MovieEvaluationQueryRequest;
import com.wgb.movie.model.dto.movieEvaluation.MovieEvaluationUpdateRequest;
import com.wgb.movie.model.entity.MovieEvaluation;
import com.wgb.movie.model.entity.User;
import com.wgb.movie.model.vo.MovieEvaluationVO;
import com.wgb.movie.service.MovieEvaluationService;
import com.wgb.movie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 评价接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/movieEvaluation")
@Slf4j
public class MovieEvaluationController {

    @Resource
    private MovieEvaluationService movieEvaluationService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建评价
     *
     * @param movieEvaluationAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addMovieEvaluation(@RequestBody MovieEvaluationAddRequest movieEvaluationAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(movieEvaluationAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        MovieEvaluation movieEvaluation = new MovieEvaluation();
        BeanUtils.copyProperties(movieEvaluationAddRequest, movieEvaluation);
        User loginUser = userService.getLoginUser(request);
        movieEvaluation.setUserId(loginUser.getId());
        // 数据校验
        movieEvaluationService.validMovieEvaluation(movieEvaluation, true);
        // todo 填充默认值

        // 写入数据库
        boolean result = movieEvaluationService.save(movieEvaluation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newMovieEvaluationId = movieEvaluation.getId();
        return ResultUtils.success(newMovieEvaluationId);
    }

    /**
     * 删除评价
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteMovieEvaluation(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        MovieEvaluation oldMovieEvaluation = movieEvaluationService.getById(id);
        ThrowUtils.throwIf(oldMovieEvaluation == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldMovieEvaluation.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = movieEvaluationService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新评价（仅管理员可用）
     *
     * @param movieEvaluationUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateMovieEvaluation(@RequestBody MovieEvaluationUpdateRequest movieEvaluationUpdateRequest) {
        if (movieEvaluationUpdateRequest == null || movieEvaluationUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        MovieEvaluation movieEvaluation = new MovieEvaluation();
        BeanUtils.copyProperties(movieEvaluationUpdateRequest, movieEvaluation);
        // 数据校验
        movieEvaluationService.validMovieEvaluation(movieEvaluation, false);
        // 判断是否存在
        long id = movieEvaluationUpdateRequest.getId();
        MovieEvaluation oldMovieEvaluation = movieEvaluationService.getById(id);
        ThrowUtils.throwIf(oldMovieEvaluation == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = movieEvaluationService.updateById(movieEvaluation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取评价（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<MovieEvaluationVO> getMovieEvaluationVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        MovieEvaluation movieEvaluation = movieEvaluationService.getById(id);
        ThrowUtils.throwIf(movieEvaluation == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(movieEvaluationService.getMovieEvaluationVO(movieEvaluation, request));
    }

    /**
     * 分页获取评价列表（仅管理员可用）
     *
     * @param movieEvaluationQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MovieEvaluation>> listMovieEvaluationByPage(@RequestBody MovieEvaluationQueryRequest movieEvaluationQueryRequest) {
        long current = movieEvaluationQueryRequest.getCurrent();
        long size = movieEvaluationQueryRequest.getPageSize();
        // 查询数据库
        Page<MovieEvaluation> movieEvaluationPage = movieEvaluationService.page(new Page<>(current, size),
                movieEvaluationService.getQueryWrapper(movieEvaluationQueryRequest));
        return ResultUtils.success(movieEvaluationPage);
    }

    /**
     * 分页获取评价列表（封装类）
     *
     * @param movieEvaluationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<MovieEvaluationVO>> listMovieEvaluationVOByPage(@RequestBody MovieEvaluationQueryRequest movieEvaluationQueryRequest,
                                                                             HttpServletRequest request) {
        long current = movieEvaluationQueryRequest.getCurrent();
        long size = movieEvaluationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<MovieEvaluation> movieEvaluationPage = movieEvaluationService.page(new Page<>(current, size),
                movieEvaluationService.getQueryWrapper(movieEvaluationQueryRequest));
        // 获取封装类
        return ResultUtils.success(movieEvaluationService.getMovieEvaluationVOPage(movieEvaluationPage, request));
    }

    /**
     * 分页获取当前登录用户创建的评价列表
     *
     * @param movieEvaluationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<MovieEvaluationVO>> listMyMovieEvaluationVOByPage(@RequestBody MovieEvaluationQueryRequest movieEvaluationQueryRequest,
                                                                               HttpServletRequest request) {
        ThrowUtils.throwIf(movieEvaluationQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        movieEvaluationQueryRequest.setUserId(loginUser.getId());
        long current = movieEvaluationQueryRequest.getCurrent();
        long size = movieEvaluationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<MovieEvaluation> movieEvaluationPage = movieEvaluationService.page(new Page<>(current, size),
                movieEvaluationService.getQueryWrapper(movieEvaluationQueryRequest));
        // 获取封装类
        return ResultUtils.success(movieEvaluationService.getMovieEvaluationVOPage(movieEvaluationPage, request));
    }

    /**
     * 编辑评价（给用户使用）
     *
     * @param movieEvaluationEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editMovieEvaluation(@RequestBody MovieEvaluationEditRequest movieEvaluationEditRequest, HttpServletRequest request) {
        if (movieEvaluationEditRequest == null || movieEvaluationEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        MovieEvaluation movieEvaluation = new MovieEvaluation();
        BeanUtils.copyProperties(movieEvaluationEditRequest, movieEvaluation);
        // 数据校验
        movieEvaluationService.validMovieEvaluation(movieEvaluation, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = movieEvaluationEditRequest.getId();
        MovieEvaluation oldMovieEvaluation = movieEvaluationService.getById(id);
        ThrowUtils.throwIf(oldMovieEvaluation == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldMovieEvaluation.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = movieEvaluationService.updateById(movieEvaluation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
